package com.hankol.winecellar

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.winecellar.adapter.PrivateMealAdapter
import com.hankol.winecellar.bean.PrivateMealManageListBean
import com.hankol.winecellar.bean.WineryCoverBean
import com.hankol.winecellar.databinding.ActivityPrivateMealManageBinding
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import java.util.ArrayList

/**私房下酒菜管理
 * @author: merbng
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.WINCE_PRIVATE_MEAL_MANAGER)
class PrivateMealManageActivity : BaseActivity(), View.OnClickListener {

    private lateinit var viewModel: WineCellarViewModel
    private lateinit var binding: ActivityPrivateMealManageBinding
    val mAdapter: PrivateMealAdapter by lazy { PrivateMealAdapter() }
    private var hasnext: Boolean = false
    var page = 1
    var currentPos = 0

    override fun getLayoutId(): Int {
        return R.layout.activity_private_meal_manage
    }

    override fun init() {
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        initView()
        initListener()
        initObserver()
    }

    private fun initListener() {
        binding.imgBack.setOnClickListener(this)
        binding.imgAdd.setOnClickListener(this)

        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val bean = adapter.data[position] as PrivateMealManageListBean
            }
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val bean = adapter.data[position] as PrivateMealManageListBean
                when (view.id) {
                    R.id.tv_edit -> {
                        val bundle = Bundle()
                        bundle.putParcelable(Constants.KEY_PRIVATE_MEAL_BEAN, bean)
                        ActivityRouter.startActivity(
                            ActivityRouter.WINE_CELLAR.PUBLISH_PRIVATE_MEAL,
                            bundle
                        )
                    }
                    R.id.tv_delete -> {
                        currentPos = position
                        deleteOption(bean.id)
                    }
                    R.id.rimg_cover -> {
                        val urlList = mutableListOf<String>()
                        val titleList = mutableListOf<String>()
                        val descList = mutableListOf<String>()
                        for (datum in adapter.data as List<PrivateMealManageListBean>) {
                            val coverBean = CommonUtil.jsonToBean(
                                datum.appetizerImg.checkValue(),
                                WineryCoverBean::class.java
                            )
                            urlList.add(if (coverBean.type == 0) coverBean.coverUrl else coverBean.videoUrl)
                            titleList.add(datum.appetizerName)
                            descList.add(datum.appetizerDesc)
                        }
                        seeBigImg(urlList, position, titleList, descList)
                    }
                }
            }
        }

        binding.smartRefresh.setOnRefreshListener {
            page = 1
            loadData()
        }
        binding.smartRefresh.setOnLoadMoreListener {
            if (hasnext) {
                loadData()
            } else {
                binding.smartRefresh.finishLoadMore()
            }
        }
    }

    private fun seeBigImg(
        coverUrlList: MutableList<String>,
        position: Int,
        titleList: List<String>,
        descList: List<String>
    ) {
        //查看大图
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.KEY_URLS, coverUrlList as ArrayList<String>)
        bundle.putInt(Constants.KEY_INDEX, position)
        bundle.putStringArrayList(
            Constants.KEY_COMMENT_CONTENT,
            if (descList.size == 0) ArrayList<String>() else descList as ArrayList<String>
        )
        bundle.putStringArrayList(
            Constants.KEY_COMMENT_TITLE,
            if (titleList.size == 0) ArrayList<String>() else titleList as ArrayList<String>
        )
        ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.IMG_VIDEO_DETAIL, bundle)
    }

    private fun deleteOption(id: Int) {
        PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
            override fun clickOk() {
                viewModel.reqDeletePrivateMeal(id)
            }

            override fun clickCancel() {

            }

        }, false, "确认", "取消")
    }

    private fun initView() {
        binding.rvList.setAdapter(mAdapter)
    }

    private fun initObserver() {
        viewModel.privateMealListLD.observe(this, Observer {
            hideLoadingDialog()
            binding.smartRefresh.finishRefresh()
            if (it.data?.size == 0 && page == 1) {//首次为空
                mAdapter.emptyView = EmptyViewUtil.getEmptyView4Winecellar(
                    binding.rvList,
                    "发布酒窖力推菜品，让用户一眼爱上TA，添加成功后，在“线上酒窖”进行预览（长按更换排序）",
                    R.drawable.ic_empty_demo_private_meal
                )
            } else {
                if (page == 1) {
                    mAdapter.setNewData(it.data)
                } else {
                    mAdapter.addData(it.data!!)
                    binding.smartRefresh.finishLoadMore()
                }
                if (it.data.checkNotNull()) {
                    hasnext = it.totalCount != mAdapter.data.size
                }
                page++
            }
        })
        viewModel.deletePrivateMealLD.observe(this, Observer {
            if (it.checkNotNull() && it) {
                //删除下酒菜
                mAdapter.remove(currentPos)
                if (mAdapter.data.size == 0) {//首次为空
                    mAdapter.emptyView = EmptyViewUtil.getEmptyView4Winecellar(
                        binding.rvList,
                        "发布酒窖力推菜品，让用户一眼爱上TA添加成功后，在“线上酒窖”进行预览（长按更换排序）",
                        R.drawable.ic_empty_demo_private_meal
                    )
                }
                ToastUtils.showShort(applicationContext, "删除成功")
                mAdapter.notifyDataSetChanged()
            }
        })
    }

    fun loadData() {
        showLoadingDialog()
        val wineryCode = SpUtils.getInstance().currentWineryInfo.wineryCode
        viewModel.reqPrivateMealList(wineryCode, page)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.img_back -> {
                finish()
            }
            R.id.img_add -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    ARouterUtils.jump(ActivityRouter.WINE_CELLAR.PUBLISH_PRIVATE_MEAL)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        page = 1
        loadData()
    }
}